<template>
  <div class="app-container">
    <div id="steps" class="m-b-10">
      <el-steps :active="active" finish-status="success" align-center>
        <el-step title="课程基本信息"></el-step>
        <el-step title="课程大纲"></el-step>
        <el-step title="发布课程"></el-step>
      </el-steps>
    </div>
    <div id="uploadForm" v-show="active == 1">
      <el-form
        ref="uploadCourseForm"
        :model="uploadCourseForm"
        label-width="80px"
        status-icon
        :rules="courseRules"
      >
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="uploadCourseForm.courseName"></el-input>
        </el-form-item>
        <el-form-item label="课程封面">
          <el-row>
            <el-col :span="12">
              <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-success="handleAvatarSuccess"
                :auto-upload="false"
                :on-change="handleChange"
              >
                <el-button slot="trigger" size="small" type="primary"
                  >选取文件</el-button
                >
                <el-button
                  style="margin-left: 10px"
                  size="small"
                  type="success"
                  @click="submitUploadCoverImage"
                  >上传到服务器</el-button
                >
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-col>
            <el-col :span="12">
              <el-image
                style="width: 200px; height: 100px"
                :src="src"
                v-show="showCoverImae"
              ></el-image>
            </el-col>
          </el-row>
        </el-form-item>
<!--        <div v-if="courseAdmin">-->
<!--          <el-form-item label="课程类型">-->
<!--            <el-select-->
<!--              v-model="uploadCourseForm.courseTypeIdList"-->
<!--              multiple-->
<!--              filterable-->
<!--              clearable-->
<!--              placeholder="请选择"-->
<!--            >-->
<!--              <el-option-group-->
<!--                v-for="(group,index) in courseOptions"-->
<!--                :key="index"-->
<!--                :label="group.label"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="item in group.options"-->
<!--                  :key="item.courseTypeId"-->
<!--                  :label="item.typeName"-->
<!--                  :value="item.courseTypeId"-->
<!--                >-->
<!--                </el-option>-->
<!--              </el-option-group>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="课程学分">-->
<!--            <el-input-number-->
<!--              v-model="uploadCourseForm.credit"-->
<!--              :step="2"-->
<!--              type="number"-->
<!--            ></el-input-number>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="课程码">-->
<!--            <el-row>-->
<!--              <el-col :span="6">-->
<!--                <el-switch-->
<!--                  v-model="isNeedReciver"-->
<!--                  active-text="需要邀请码"-->
<!--                  inactive-text="不需要邀请码"-->
<!--                >-->
<!--                </el-switch>-->
<!--              </el-col>-->
<!--              <el-col :span="6">-->
<!--                <el-switch-->
<!--                  v-model="open"-->
<!--                  active-text="公开"-->
<!--                  inactive-text="不公开"-->
<!--                >-->
<!--                </el-switch>-->
<!--              </el-col>-->
<!--            </el-row>-->

<!--            <el-row>-->
<!--              <el-col :span="12"-->
<!--                ><el-input-->
<!--                  v-model="uploadCourseForm.reciverUrls"-->
<!--                  v-show="isNeedReciver"-->
<!--                  :disabled="true"-->
<!--                ></el-input-->
<!--              ></el-col>-->
<!--            </el-row>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="教师信息">-->
<!--            <el-cascader-->
<!--            style="width:auto"-->
<!--            clearable-->
<!--            filterable-->
<!--              v-model="teacherValue"-->
<!--              :options="departMentOptions"-->
<!--              :props="{ expandTrigger: 'hover' }"-->
<!--              @change="handleCascaderChange"></el-cascader>-->
<!--          </el-form-item>-->
<!--        </div>-->

        <el-form-item label="课程描述">
          <el-input
            type="textarea"
            v-model="uploadCourseForm.descriptions"

          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addCourse('uploadCourseForm')">{{
            uploadButtonText
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="step2" v-show="active == 2">
      <div id="step2-dialog">
        <el-dialog title="新建章节" :visible.sync="dialog_newChapter">
          <el-form :model="dynamicValidateForm"  label-width="100px" class="demo-dynamic">
            <el-form-item label="章节名称" :label-width="formLabelWidth">
             <el-row>
               <el-col :span="18"
                  >
                  <el-input
                v-model="dynamicValidateForm.courseName"
                autocomplete="off"
              ></el-input>
                  </el-col>
                     <el-col :span="6"
                  >
                  <el-button type="warning" icon="el-icon-plus" circle @click="addDomain"></el-button>
                  </el-col>
               </el-row>

            </el-form-item>

            <el-form-item
              v-for="(domain, index) in dynamicValidateForm.domains"
              :label="'子章节名称' + index"
              :key="domain.key"
            >
              <el-row>
               <el-col :span="18"
                  >
                  <el-input v-model="domain.value"></el-input
              ></el-input>
                  </el-col>
                     <el-col :span="6"
                  >
                  <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click.prevent="removeDomain(domain)"
              ></el-button>

                  </el-col>
               </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addChapter()">提交</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div>
        <el-button type="primary" class="f-r" @click="dialog_newChapter = true"
          >新建章节<i class="el-icon-upload el-icon--right"></i
        ></el-button>
      </div>
      <br />
      <div>
        <el-collapse @change="handleCollapseChange">
          <el-collapse-item
            v-for="item in chapterList"
            :title="item.courseInfo.courseName"
            :name="item.courseInfo.courseId"
            :key="item.courseInfo.courseId"
          >
            <template slot="title" style="position: relative">
              <span>{{item.courseInfo.courseName}}</span>
              <el-button
                type="primary" size="mini"
                style="position:absolute; right:300px;"
                @click="editTitle(item)">编辑标题</el-button>
            </template>
            <div  v-for="sonCourse in item.sonCourseInfo"
                  :key="sonCourse.courseId">
              <el-card shadow="hover">
                {{sonCourse.courseName}}
                <router-link
                :to="{
                  name: 'uploadCourseMaterial',
                  query: { courseId: sonCourse.courseId },
                }"
                class="f-r"
              >
                <el-button size="small" type="info">上传课程资料</el-button>
              </router-link>
                
              </el-card>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-dialog title="编辑章节标题" :visible.sync="dialog_editChapter">
          <el-form :model="editForm"  label-width="100px" class="demo-dynamic">
            <el-form-item label="章节名称" :label-width="formLabelWidth">
              <el-row>
                <el-col :span="18">
                  <el-input
                    v-model="editForm.courseName"
                    autocomplete="off"></el-input>
                </el-col>
                <el-col :span="6">
                  <el-button type="warning" icon="el-icon-plus" circle @click="editaddDomain"></el-button>
                </el-col>
              </el-row>

            </el-form-item>

            <el-form-item
              v-for="(domain, index) in editForm.domains"
              :label="'子章节名称' + index"
              :key="domain.key"
            >
              <el-row>
                <el-col :span="18"
                >
                  <el-input v-model="domain.value"></el-input>
                </el-col>
                <el-col :span="6"
                >
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click.prevent="editremoveDomain(domain)"
                  ></el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="editChapter()">提交编辑</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <div id='btn' class="f-r">
            <el-button-group>
            <el-button type="primary" icon="el-icon-arrow-left" @click="active = 1">上一步</el-button>
            <el-button type="primary" @click="stepTo3">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
      </el-button-group>
        </div>
      </div>
    </div>
    <div v-show="active==3">
    <el-row :gutter="12">
  <el-col :span="12">
    <el-card shadow="always">
     <el-image :src="courseInfo.coverImage"></el-image>
    </el-card>
  </el-col>
  <el-col :span="12">
    <el-card shadow="hover">
      <h1>{{courseInfo.courseName}}</h1>
      <h3><span class="f-14">教师：</span>{{courseInfo.teacherName}}</h3>
      <el-tag   v-for="(item,index) in courseInfo.couseTypeNames"
      :key="index" :type="tagType[index%5]">{{item}}</el-tag>
      <h3 class="f-c-red">学分：{{courseInfo.credit}}</h3>
        <el-card shadow="always">
        <el-tag type="info">描述：</el-tag>

      {{courseInfo.descriptions}}
    </el-card>

    </el-card>
  </el-col>
  <el-button-group class="f-r">
            <el-button plain icon="el-icon-arrow-left" @click="active = 2">上一步</el-button>
            <el-button plain @click="finishCourse">发布课程</el-button>
      </el-button-group>
</el-row>
    </div>
  </div>
</template>

<script>
import DropdownMenu from "@/components/Share/DropdownMenu";
import {
  getCourseType,
  addCourse,
  getCourse,
  deleteCourse,
  addChapter,
  getChapterByCourseId,
  getCourseByCourseId,
  getCompanyInfoWithTeacherList,
  deleteChapter,
  updateChapter
} from "../uploadCourse_CourseAmin/uploadCourse.js";
import $ from "jquery";
import moment from "moment";
import { formatTime } from "@/utils/index.js";
import { AddOrSublineDays } from "@/utils/TimeUitls.js";
import {
  isNull,
  warnInfo,
  successInfo,
  getHost,
  getCookie,
} from "../../utils/commonUtils.js";
export default {
  name: "Documentation",
  components: { DropdownMenu },
  data() {
    var validateNull = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("不能为空"));
      } else {
      }
    };
    return {
      //进度条
      active: 1,
      courseIds: [],
      showCoverImae: false,
      src: undefined,
      courseOptions: [],
      isNeedReciver: false,
      open: false,
      uploadButtonText: "下一步",
      courseCoverImageFileList: [],
      coverImage: undefined,
      currentCourseId: undefined,
      /**父级id */
      //课程id
      pid: undefined,
      courseRules: {
        courseName: [{ required: true, message:"课程名称不得为空", trigger: "blur" }],
      },
      /**form */
      //课程信息form
      uploadCourseForm: {},
      //课程章节form
      chapterForm: {},
      editForm:{
        domains: [
          {
            value: "",
            courseId:"",
          },
        ],
        courseName: "",
        courseId:"",
      },
      /**dialog显示 */
      dialog_newChapter: false,
      dialog_editChapter:false,
      /**collapse */
      //chapter
      activeNames: [],
      /**list */
      chapterList: [],
      materrialList: [],
      formLabelWidth: "120px",
      dynamicValidateForm: {
        domains: [
          {
            value: "",
          },
        ],
        courseName: "",
      },
      //课程信息
      courseInfo: {},
      tagType: ["", "success", "info", "warning", "danger"],
      //如果是课程管理员则为true
      courseAdmin: "",
      //课程管理员跳转页面时传递的参数
      admin_courseId: undefined,
      departMentOptions: [],
      teacherValue: [],
    };
  },
  watch: {
    open(val) {
      if (val) {
        this.uploadCourseForm.open = 1;
      } else {
        this.uploadCourseForm.open = 0;
      }
    },
    isNeedReciver(val) {
      if (val) {
        this.uploadCourseForm.isNeedReciver = 1;
        this.uploadCourseForm.reciverUrls = new Date().getTime();
      } else {
        this.uploadCourseForm.isNeedReciver = 0;
        this.uploadCourseForm.reciverUrls = undefined;
      }
    },
    src(val) {
      const _this = this;
      if (isNull(val)) {
        _this.showCoverImae = false;
      } else {
        _this.showCoverImae = true;
      }
    },
  },
  created() {
    //获取正在上传的课程列表
    this.currentCourseId = this.$route.query.courseId;
    this.courseAdmin = this.$route.query.courseAdmin;
    if (this.currentCourseId != null) {
      this.active = 2;
      this.getCourse();
    }
    this.courseAdmin = this.$route.query.courseAdmin;
    if (isNull(this.courseAdmin)) {
      this.courseAdmin = false;
    }
    if (this.courseAdmin) {
      //获取课程类型列表
      this.getCourseType();
      //获取讲师信息列表
      this.getDepartmentAndTeacherList();
    }
    this.admin_courseId = this.$route.query.admin_courseId;
    if (!isNull(this.admin_courseId)) {
      this.currentCourseId = this.admin_courseId;
      this.getCourse();
    }
  },
  methods: {
    editChapter(){
      updateChapter(this.editForm).then((response) => {
        this.dialog_editChapter = false;
        this.getChapter();
      })
    },
    editremoveDomain(item){
      var index = this.editForm.domains.indexOf(item);
      if (index !== -1) {
        this.editForm.domains.splice(index, 1);
      }
      if(item.courseId!=""){
        deleteChapter(item.courseId).then((response) => {
          this.getChapter();
        })
      }
    },
    editaddDomain(){
      this.editForm.domains.push({
        value: "",
        key: Date.now(),
        courseId:"",
      });
    },
    editTitle(item){
      /*父章节赋值*/
      this.editForm.courseName = item.courseInfo.courseName;
      this.editForm.courseId = item.courseInfo.courseId;
      /*子章节赋值*/
      this.editForm.domains=[];
      const _this = this;
      item.sonCourseInfo.forEach(function(son,index){
        var sondata= {
          value: son.courseName,
          courseId:son.courseId,
        };
        _this.editForm.domains.push(sondata);
      })
      /*打开编辑标题对话框*/
      this.dialog_editChapter = true;
    },
    handleCascaderChange(value) {
      if (!isNull(value)) {
        this.uploadCourseForm.teacherIds = value[value.length - 1];
      }
    },
    /**获取部门列表以及对应的讲师信息**/
    getDepartmentAndTeacherList() {
      const _this = this;
      _this.departMentOptions = []; //首先清除信息
      getCompanyInfoWithTeacherList().then((response) => {
        $(response.data).each(function (index, value) {
          let options = {
            value: undefined,
            label: undefined,
            children: [],
          };
          //第一层信息
          options.value = value.companyId;
          options.label = value.companyName;
          let children = [];
          let childrenOption = {
            value: undefined,
            label: undefined,
          };
          //第二层信息
          $(value.tbUsers).each(function (index, value) {
            childrenOption.value = value.userId;
            childrenOption.label = value.userName;
            children.push(childrenOption);
            options.children = children;
            _this.departMentOptions.push(options);
          });
        });
      });
    },
    //发布课程
    finishCourse() {
      const _this = this;
      //课程管理员的话跳转到课程管理页面
      if (_this.courseAdmin) {
        this.$router.push({
          // path: "../courseManagement/courseManagement",
          name:"courseManagement",
        });
      } else {
        //清空
        (this.uploadCourseForm = {}), (this.courseInfo = {});
        this.src = undefined;
        this.pid = undefined;
        successInfo(_this, "课程发布成功");
        this.active = 1;
      }
    },
    /**
     * 跳到第三步
     * **/
    stepTo3() {
      this.active = 3;
      this.getCourseDetail();
    },
    /**
     * 获取课程详细信息
     * **/
    getCourseDetail() {
      const _this = this;
      var searchForm = {
        courseId: this.pid,
      };
      getCourseByCourseId(searchForm).then((response) => {
        this.courseInfo = response.data;
      });
    },
    /**Domina */
    removeDomain(item) {
      var index = this.dynamicValidateForm.domains.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1);
      }
    },
    addDomain() {
      this.dynamicValidateForm.domains.push({
        value: "",
        key: Date.now(),
      });
    },
    //获取子章节
    getChapter() {
      const _this = this;
      var searchForm = {
        courseId: _this.pid,
      };
      getChapterByCourseId(searchForm).then((response) => {
        _this.chapterList = response.data;
      });
    },
    //collapse
    handleCollapseChange(val) {},
    //新增章节
    addChapter() {
      const _this = this;
      _this.dynamicValidateForm.pid = _this.pid; //设置父级Id
      addChapter(_this.dynamicValidateForm).then((response) => {
        _this.dialog_newChapter = false;
        _this.dynamicValidateForm = {
          domains: [
            {
              value: "",
            },
          ],
          courseName: "",
        };
        _this.getChapter();
      });
    },
    /**
     *
     * **/
    deleteCourseInfo(courseId) {
      var course = {
        courseId: courseId,
      };
      deleteCourse(course).then((response) => {
        this.courseIds.pop(courseId);
      });
    },
    /**
     * 获取指定id的课程信息
     * **/
    getCourse() {
      const _this = this;
      var course = {
        courseId: this.currentCourseId,
      };
      getCourse(course).then((response) => {
        this.pid = response.data.courseId;
        if (_this.active == 2) {
          _this.getChapter();
        }
        //开始填充表单数据
        this.uploadCourseForm = response.data;
        //填充教师信息
        _this.teacherValue.push(response.data.departmentId)
         _this.teacherValue.push(response.data.teacherIds)
        this.src = this.uploadCourseForm.coverImage;
        //回溯邀请码，公开
        if (this.uploadCourseForm.isNeedReciver == 1) {
          _this.isNeedReciver = true;
        } else {
          _this.isNeedReciver = false;
        }
        if (this.uploadCourseForm.open == 1) {
          _this.open = true;
        } else {
          _this.open = false;
        }
      });
    },
    /**
     * 新增课程
     * **/
    addCourse(formName) {
      const _this = this;
      this.$refs.uploadCourseForm.validate((valid) => {
        if(valid){
          this.uploadCourseForm.coverImage = this.coverImage;
          if (!this.open) {
            this.uploadCourseForm.open = 0;
          } else {
            this.uploadCourseForm.open = 1;
          }
          if (!isNull(_this.pid)) {
            this.uploadCourseForm.courseId = _this.pid;
          }
          addCourse(this.uploadCourseForm).then((response) => {
            //设置课程的id
            _this.pid = response.data.cid;
            _this.active = 2;
            //获取子章节的信息
            _this.getChapter();

            //清除路由
            this.$router.push({ query: {} });
          });
        }
      })
    },
    /**
     * 获取课程类型
     */
    getCourseType() {
      const _this = this;
      var searchForm = {
        typeName: undefined,
      };
      getCourseType(searchForm).then((response) => {
        _this.courseOptions = response.data;
      });
    },
    /**
     * 提交头像
     */
    submitUploadCoverImage() {
      const _this = this;
      if (this.courseCoverImageFileList.length > 0) {
        this.src = URL.createObjectURL(this.courseCoverImageFileList[0].raw);
        const formData = new FormData();
        formData.append("file", this.courseCoverImageFileList[0].raw);
        formData.append(
          "fileName",
          _this.uploadCourseForm.courseName + new Date().getTime()
        );

        $.ajax({
          url: getHost() + "/fileCenter/file/uploadCourseCoverImage",
          data: formData,
          dataType: "json",
          type: "post",
          processData: false, // 告诉jQuery不要去处理发送的数据
          contentType: false, // 告诉jQuery不要去设置Content-Type请求头
          //加上这句话,允许浏览器向服务器跨域请求时携带cookie
          xhrFields: {
            withCredentials: true,
          },
          crossDomain: true,
          success: function (data) {
            _this.coverImage = data.data;
            successInfo(_this, data.message);
          },
          error: function (data) {},
        });
      } else {
        warnInfo(_this, "您未选择任何文件");
        return false;
      }
    },
    handleAvatarSuccess(res, file) {
      this.src = URL.createObjectURL(file.raw);
    },
    handleRemove(file, fileList) {
      if (fileList.length <= 0) {
        this.src = undefined;
      }
    },

    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleChange(file, fileList) {
      this.courseCoverImageFileList = fileList;
      if (this.courseCoverImageFileList.length > 0) {
        this.src = URL.createObjectURL(this.courseCoverImageFileList[0].raw);
      } else {
        this.src = undefined;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../styles/common.css";
.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>
